package com.zyc.webtest.service.impl;

import com.zyc.webtest.service.BaseService;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/***
 * 
 * 类名称：BaseServiceImpl<br>
 * 类描述： BaseService的抽象实现，供继承<br>
 * @version v1.0
 * @param <T>
 * @param <ID>
 */
@Transactional
public abstract class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID> {

    public abstract JpaRepository<T, ID> getDao();

    @Override
    public Optional<T> save(T t) {
//        return t.map(a->getDao().save(a));
        return Optional.ofNullable(getDao().save(t));
    }

    @Override
    public void save(List<T> tList) {
        getDao().save(tList);
//        tList.stream().forEach(a->getDao().save(a));
    }

    @Override
    public void delete(ID id) {
        getDao().delete(id);
    }

    @Override
    public void delete(T t) {
        getDao().delete(t);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<T> findById(ID id) {
        return Optional.ofNullable(getDao().findOne(id));
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<List<T>> findAll() {
        return Optional.ofNullable((List<T>) getDao().findAll());
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<List<T>> findAll(Sort sort) {
        return Optional.ofNullable((List<T>) getDao().findAll(sort));
    }

    @Override
    public void delete(List<T> t) {
        getDao().delete(t);
    }

    @Override
    public void delete(ID[] t) {
        Stream.of(t).forEach(id->getDao().delete(id));
    }
}
